from flask import Blueprint, request
from utilsapp.mysql_con import db_pagelist, db_fetchone, db_delete, db_update,db_insert
from utilsapp.common import assign_value, parsing_data_id

bluePrint = Blueprint('baoxiu', __name__)
tableName = 'baoxiu'


# 分页查询
@bluePrint.route('/getlist', methods=["post"])
def table_list():
    sql = f"""SELECT b.*,d.device_name from baoxiu b
left JOIN device d on d.id = b.device_id"""
    query = " where 1 = 1 and b.isDel = 1 "
    a = request.json
    scope_id = assign_value(a, "scope_id", 0)
    scoped = parsing_data_id(scope_id, request)
    device_name = assign_value(a, "device_name")
    reporter = assign_value(a,"reporter")
    sectioner = assign_value(a,"sectioner")
    state = assign_value(a, "state")
    if scoped != "":
        query += f" and d.{scoped}"
    if device_name != '':
        query += f" and d.device_name like '%{device_name}%' "
    if reporter !="":
        query += f" and b.reporter like '%{reporter}%' "
    if sectioner !="":
        query += f" and b.sectioner like '%{sectioner}%' "
    if state != "":
        query += f" and b.state = {state}"
    sql += query
    sql_ = f"select count(state) as num from ({sql}) as a where state = "
    num1 = db_fetchone(sql_+'1')
    num2 = db_fetchone(sql_+'2')
    num3 = db_fetchone(sql_+'3')
    res = db_pagelist(sql, a["page"])
    res['stat'] = {
        "pending": num1['data'],
        "completed": num2['data'],
        "unCompleted": num3['data'],
    }
    return res



@bluePrint.route('/add', methods=['POST'])
def project_add():
    request.json['isDel'] = 1
    return db_insert(tableName, request.json)



@bluePrint.route('/delete', methods=["post"])
def a():
    id_ = assign_value(request.json, "id")
    return db_update(tableName,{"isDel":2}, f'WHERE id = %s',
                     {'id_': id_})



@bluePrint.route("/edit", methods=['post'])
def b():
    id_ = assign_value(request.json, "id")
    return db_update(tableName,request.json,f"where id =%s", {"id_": id_})
